﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NBear.Mapping;
using System.Collections.Specialized;
using MySoft.Data;
//using KingRoad.EPM.InvestmeEntity;
using System.Data;
using AutoMapper;
using System.Reflection;
using Aspose.Cells;
using DotNet.Model.MyEntity;
using DotNet.Service;
//using KingRoad.EPM.FundBLL;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace KingRoad.EPM.Web.Util
{
    /// <summary>
    /// WebUtility
    /// UI辅助方法。
    /// 
    /// 修改纪录
    /// 
    /// 版本：1.0
    /// 
    /// <author>
    ///		<name>WS</name>
    ///		<date>2011.08.15</date>
    /// </author> 
    /// </summary>
    public static class WebUtility
    {
        /// <summary>
        /// 将分页查询信息转换为对象
        /// </summary>
        /// <param name="query"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static object ConvertQueryToObject(string query, object t)
        {
            if (string.IsNullOrWhiteSpace(query)) return null;

            query = HttpContext.Current.Server.UrlDecode(query);

            ObjectMapper mapper = new ObjectMapper(typeof(NameValueCollection), t.GetType());

            NameValueCollection v = GetValueCollection(query);
            //保存原对象分页信息
            QueryBase page = t as QueryBase;
            t = mapper.ConvertObject(v);
            QueryBase qb1 = t as QueryBase;
            if (page != null && qb1 != null)
            {
                QueryBase qq = (QueryBase)t;
                qq.page = page.page;
                qq.records = page.records;
                qq.total = page.total;
                qq.rows = page.rows;
                qq.sidx = page.sidx;
                qq.sord = page.sord;
                qq._search = page._search;
            }
            return t;
        }
        /// <summary>
        /// 分页外链表转换 WS 2012.5.19
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static jqGridQueryData<T> ToJqGridData<T>(IDataPage<DataTable> data)
            where T : class
        {
            jqGridQueryData<T> jqData = new jqGridQueryData<T>();

            jqData.page = data.CurrentPageIndex;
            jqData.records = data.RowCount;
            jqData.total = data.PageCount;
            //强制转换
            jqData.rows = Mapper.DynamicMap<IDataReader, List<T>>(data.DataSource.CreateDataReader());
            return jqData;
        }
        public static NameValueCollection GetValueCollection(string query)
        {
            NameValueCollection v = new NameValueCollection();
            foreach (var s in query.Split('&'))
            {
                var ss = s.Split('=');
                if (ss.Length > 1)
                {
                    v.Add(ss[0], ss[1]);
                }
            }
            return v;
        }

        /// <summary>
        /// 将查询结果进行包装成复合jqGrid的数据要求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public static jqGridQueryData<T> TojqGridData<T>(IList<T> dataList, QueryBase query)
        {
            jqGridQueryData<T> data = new jqGridQueryData<T>();

            data.page = query.page;
            data.records = query.records;
            data.total = query.total;

            data.rows = dataList;
            return data;
        }

        /// <summary>
        /// 将分页数据转换为jqGrid格式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public static jqGridQueryData<T> TojqGridData<T>(IDataPage<IList<T>> dataList)
        {
            jqGridQueryData<T> data = new jqGridQueryData<T>();
            if (dataList.DataSource != null)
            {
                data.page = dataList.CurrentPageIndex;
                data.records = dataList.RowCount;
                data.total = dataList.PageCount;
                data.rows = dataList.DataSource;
            }
            return data;
        }
        /// <summary>
        /// 将用户列表分页数据转换为jqGrid格式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public static jqGridQueryData<T> User_TojqGridData<T>(IDataPage<IList<T>> dataList, QueryBase queryBase)
        {
            jqGridQueryData<T> data = new jqGridQueryData<T>();
            IList<T> templist = new List<T>();
            if (dataList.DataSource != null)
            {
                templist = dataList.DataSource;
                data.page = queryBase.page;
                data.records = queryBase.records;
                data.total = queryBase.total;
                data.rows = templist;
            }
            return data;
        }
        /// <summary>
        /// Convert a List{T} to a DataTable.
        /// </summary>
        public static DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }

        /// <summary>
        /// Determine of specified type is nullable
        /// </summary>
        private static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        /// <summary>
        /// Return underlying type if type is Nullable otherwise return the type
        /// </summary>
        private static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static DataTable CreateData<T>(T model)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }
            var values = new object[props.Length];
            for (int i = 0; i < props.Length; i++)
            {
                values[i] = props[i].GetValue(model, null);
            }

            tb.Rows.Add(values);

            return tb;
        }
        /// <summary>
        ///控制小数位公共方法
        /// </summary>
        /// <param name="values">保留小数位值</param>
        /// <param name="Decimals">保留小数位</param>
        /// <returns>保留后的值</returns>
        public static decimal KeepDecimals(decimal values, int Decimals)
        {
            if (values >= 0)
                values += 5 * Decimal.Parse(Math.Pow(10, -(Decimals + 1)).ToString());
            else
                values += -5 * Decimal.Parse(Math.Pow(10, -(Decimals + 1)).ToString());
            string str = values.ToString();
            string[] strs = str.Split('.');
            if (strs.Length > 1)
            {
                int idot = str.IndexOf('.');
                string prestr = strs[0];
                string poststr = strs[1];
                if (poststr.Length > Decimals)
                {
                    poststr = str.Substring(idot + 1, Decimals);
                }
                string strd = prestr + "." + poststr;
                values = Convert.ToDecimal(strd);
            }
            return values;
        }
        /// <summary>
        /// 对上传的图片进行质量压缩
        /// </summary>
        /// <param name="path">保存路径</param>
        /// <param name="FileData"></param>
        /// <param name="towidth">压缩图片宽度</param>
        /// <param name="toheight">压缩图片高度</param>
        public static void CompressionPhoto(string path, HttpPostedFileBase FileData, int towidth, int toheight)
        {
            int x = 0;
            int y = 0;

            Stream stream = FileData.InputStream;
            Image originalImage = Image.FromStream(stream);

            int ow = originalImage.Width;//获取图片的宽度
            int oh = originalImage.Height;//获取图片的高度
            if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
            {
                oh = originalImage.Height;
                ow = originalImage.Height * towidth / toheight;
                y = 0;
                x = (originalImage.Width - ow) / 2;
            }
            else
            {
                ow = originalImage.Width;
                oh = originalImage.Width * toheight / towidth;
                x = 0;
                y = (originalImage.Height - oh) / 2;
            }

            Bitmap b = new Bitmap(towidth, toheight);
            try
            {
                Graphics g = Graphics.FromImage(b);
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.Clear(Color.Transparent);
                g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);

                b.Save(path, originalImage.RawFormat);
                //b.Save(path);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                originalImage.Dispose();
                b.Dispose();
            }
        }

        /// <summary>
        /// 电子签名
        /// </summary>
        /// <param name="designer"></param>
        /// <param name="Id"></param>
        /// <param name="Type"></param>
        public static void InsertSign(WorkbookDesigner designer, int Id, int Type)
        {
            OrganizeService org = new OrganizeService();
            IList<Base_Duty> dutyList = org.GetDTDuty();
            Cell signPicCell = null;
            //Cell signIdeaCell = null;
            IList<Base_User> userlist = null;
            Worksheet sheet = designer.Workbook.Worksheets[0];
            string content = string.Empty;
            //替换 电子签名、意见、日期单元格
            foreach (Base_Duty dutyDetail in dutyList)
            {
                signPicCell = sheet.Cells.FindString(dutyDetail.Code, null);
                //signIdeaCell = sheet.Cells.FindString(dutyDetail.Code + "_idea", null);
                content = string.Empty;
                userlist = org.GetUsersByDuty(dutyDetail.ID);
                foreach (var item in userlist)
                {
                    //content = new Common_AuditOpinionBLL().GetCellData(Id, Type, 2, item.Id);
                    if (!string.IsNullOrEmpty(content)) break;
                }
                if (signPicCell != null)
                {
                    if (!string.IsNullOrEmpty(content))
                    {
                        content = System.Web.HttpContext.Current.Server.MapPath(content);
                        byte[] newByte = System.IO.File.ReadAllBytes(content);
                        //创建图像对象
                        System.IO.MemoryStream streamImg = new System.IO.MemoryStream();
                        streamImg.Write(newByte, 0, newByte.Length);
                        System.Drawing.Image img = System.Drawing.Image.FromStream(streamImg);
                        //过大的话，等比例缩放
                        int cellHeight = sheet.Cells.GetRowHeightPixel(signPicCell.Row);//单元格高度
                        int cellWidht = sheet.Cells.GetColumnWidthPixel(signPicCell.Column);//单元格宽度
                        int width = img.Width;//缩放后的宽度
                        int height = img.Height;//缩放后的高度
                        if (signPicCell.IsMerged)//如果电子签名单元格合并，就取合并区域的宽度
                        {
                            for (int i = 0; i < signPicCell.GetMergedRange().ColumnCount - 1; i++)
                            {
                                cellWidht += sheet.Cells.GetColumnWidthPixel(signPicCell.Column + i + 1);
                            }
                            for (int i = 0; i < signPicCell.GetMergedRange().RowCount - 1; i++)
                            {
                                cellHeight += sheet.Cells.GetRowHeightPixel(signPicCell.Row + i + 1);
                            }
                        }
                        if (img.Width > cellWidht || img.Height > cellHeight)
                        {
                            double widthPercent = Convert.ToDouble(img.Width) / Convert.ToDouble(cellWidht);
                            double heightPercent = Convert.ToDouble(img.Height) / Convert.ToDouble(cellHeight);
                            double percent = Math.Max(widthPercent, heightPercent);
                            width = Convert.ToInt32(img.Width / percent);
                            height = Convert.ToInt32(img.Height / percent);
                        }

                        //设置图片显示位置
                        sheet.Cells[signPicCell.Row, signPicCell.Column].PutValue("");//清除单元格内容
                        int picIndex = sheet.Pictures.Add(signPicCell.Row, signPicCell.Column, streamImg);//插入到单元格中
                        Aspose.Cells.Drawing.Picture pic = sheet.Pictures[picIndex];
                        pic.Placement = Aspose.Cells.Drawing.PlacementType.Move;
                        pic.IsLockAspectRatio = false;
                        pic.Width = (width >= cellWidht ? width - 2 : width);
                        pic.Height = (height >= cellHeight ? height - 2 : height);
                        pic.Y = pic.Y + (cellHeight - pic.Height) / 2;//图片垂直居中
                        pic.X = pic.X + (cellWidht - img.Width) / 2;//图片水平居中
                    }
                }
            }
        }
        #region 日期转换
        /// <summary>
        /// 把数字转换为大写
        /// </summary>
        /// <param name="num">数字</param>
        /// <returns>字符串</returns>
        public static string numtoUpper(int num)
        {
            String str = num.ToString();
            string rstr = "";
            int n;
            for (int i = 0; i < str.Length; i++)
            {
                n = Convert.ToInt32(str[i].ToString());//char转数字,转换为字符串，再转数字
                switch (n)
                {
                    case 0: rstr = rstr + "〇"; break;
                    case 1: rstr = rstr + "一"; break;
                    case 2: rstr = rstr + "二"; break;
                    case 3: rstr = rstr + "三"; break;
                    case 4: rstr = rstr + "四"; break;
                    case 5: rstr = rstr + "五"; break;
                    case 6: rstr = rstr + "六"; break;
                    case 7: rstr = rstr + "七"; break;
                    case 8: rstr = rstr + "八"; break;
                    default: rstr = rstr + "九"; break;
                }
            }
            return rstr;
        }
        /// <summary>
        /// 月转化为大写
        /// </summary>
        /// <param name="month">月</param>
        /// <returns></returns>
        public static string monthtoUpper(int month)
        {
            if (month < 10)
            {
                return numtoUpper(month);
            }
            else
            {
                if (month == 10)
                {
                    return "十";
                }
                else
                {
                    return "十" + numtoUpper(month - 10);
                }
            }
        }
        /// <summary>
        /// 日转化为大写
        /// </summary>
        /// <param name="day">日</param>
        /// <returns></returns>
        public static string daytoUpper(int day)
        {
            if (day < 20)
            {
                return monthtoUpper(day);
            }
            else
            {
                String str = day.ToString();
                if (str[1] == '0')
                {
                    return numtoUpper(Convert.ToInt32(str[0].ToString())) + "十";

                }
                else
                {
                    return numtoUpper(Convert.ToInt32(str[0].ToString())) + "十"
                        + numtoUpper(Convert.ToInt32(str[1].ToString()));
                }
            }
        }
        /// <summary>
        /// 日期转换为大写
        /// </summary>
        /// <param name="date">日期</param>
        /// <returns></returns>
        public static string dateToUpper(System.DateTime date)
        {
            int year = date.Year;
            int month = date.Month;
            int day = date.Day;
            return numtoUpper(year) + "年" + monthtoUpper(month) + "月" + daytoUpper(day) + "日";

        }
        #endregion
    }

    /// <summary>
    /// jqgrid返回数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class jqGridQueryData<T>
    {
        public int page { get; set; }
        public int total { get; set; }
        public int records { get; set; }
        public object userData { get; set; }
        public IList<T> rows { get; set; }
    }
}